#include "HttpManage.h"
#include<QHttpMultiPart>
#include<QTimer>
#include<QEventLoop>
#include<QJsonArray>
HttpManage::HttpManage()
{
    connect(this,&HttpManage::sig_http_finish,this,&HttpManage::slot_http_finish);
}

void HttpManage::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    QByteArray data = QJsonDocument(json).toJson();
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.length()));

    // 添加 Bearer Token（如果存在）
    if (!_token.isEmpty())
    {
        request.setRawHeader("Authorization", "Bearer " + _token.toUtf8());
    }
    if(!_uid.isEmpty())
    {
        request.setRawHeader("X-User-UID", _uid.toUtf8());
    }
    //启用 HTTPS SSL 验证（正式环境需要）
    QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    sslConfig.setPeerVerifyMode(QSslSocket::VerifyPeer);
    request.setSslConfiguration(sslConfig);

    auto self = shared_from_this();
    //用来接收发送请求后的回应
    QNetworkReply* reply = _manager.post(request,data);
    QObject::connect(reply,&QNetworkReply::finished,[self,reply,req_id,mod]()
    {
        // 获取 HTTP 状态码
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        //处理错误情况
        if(reply->error() != QNetworkReply::NoError)
        {
            qDebug()<<"Network Error:"<<reply->errorString();
            //发送信号通知出错
            emit self->sig_http_finish(req_id,"",ErrorCode::ERR_NETWORK,mod);
            reply->deleteLater();
            return ;
        }

        //无错误，读出所有数据
        QString res = reply->readAll();

        if(statusCode >=400)
        {
            qDebug()<<"http error："<<statusCode<<res;
            //特殊处理401未授权
            if(statusCode == 401)
            {
                emit self->sig_token_expired();//token过期信号
            }
        }

        //发送信号通知完成
        emit self->sig_http_finish(req_id,res,ErrorCode::SUCCESS,mod);
        reply->deleteLater();
        return ;
    });
}
void HttpManage::PostHttpMultiPartReq(QUrl url, QString header, QString body, ReqId req_id, Modules mod)
{
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,header);
    filePart.setBody(body.toUtf8());
    multiPart->append(filePart);
    //创建http请求
    QNetworkRequest request(url);
        if (!_token.isEmpty()) {
            request.setRawHeader("Authorization", "Bearer " + _token.toUtf8());
        }
        if (!_uid.isEmpty()) {
            request.setRawHeader("X-User-UID", _uid.toUtf8());
        }
        QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
        sslConfig.setPeerVerifyMode(QSslSocket::VerifyPeer);
        request.setSslConfiguration(sslConfig);

        auto self = shared_from_this();
        QNetworkReply *reply = _manager.post(request, multiPart);
    // connect(reply, &QNetworkReply::uploadProgress, [=](qint64 bytesSent, qint64 bytesTotal)
    // {
    //     emit sig_update_progress(bytesSent, bytesTotal);
    // });
    connect(reply,&QNetworkReply::finished,[self,reply,req_id,mod]()
    {
        // 获取 HTTP 状态码
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        //处理错误情况
        if(reply->error() != QNetworkReply::NoError)
        {
            qDebug()<<"Network Error:"<<reply->errorString();
            //发送信号通知出错
            emit self->sig_http_finish(req_id,"",ErrorCode::ERR_NETWORK,mod);
            reply->deleteLater();
            return ;
        }

        //无错误，读出所有数据
        QString res = reply->readAll();

        if(statusCode >=400)
        {
            qDebug()<<"http error："<<statusCode<<res;
            //特殊处理401未授权
            if(statusCode == 401)
            {
                emit self->sig_token_expired();//token过期信号
            }
        }

        //发送信号通知完成
        emit self->sig_http_finish(req_id,res,ErrorCode::SUCCESS,mod);
        reply->deleteLater();
        return ;
     });
}


QNetworkAccessManager &HttpManage::getManager()
{
    return _manager;
}



void HttpManage::setToken(const QString &token)
{
    _token = token;
}

void HttpManage::SetAuthInfo(const QString &token, QString uid , QString user)
{

    _token = token;
    _uid = uid;
    _user = user;
    // 可以在此处持久化存储到本地
    QSettings settings;
    settings.setValue("auth/token", token);
    settings.setValue("auth/uid", uid);

}

QString HttpManage::getUser()
{
    return _user;
}

QString HttpManage::getToken()
{
    return _token;
}

QString HttpManage::getUid()
{
    return _uid;
}
void HttpManage::slot_http_finish(ReqId id, QString res,ErrorCode err, Modules mod)
{
    switch(mod)
    {
        case Modules::REGISTERMOD:
            emit sig_reg_mod_finish(id, res, err);
            break;
        case Modules::GETBACK:
            emit sig_getback_mod_finish(id, res, err);
            break;
        case Modules::LOGINMOD:
            emit sig_login_mod_finish(id, res, err);
            break;
        case Modules::FILEUPLOADMOD:
            emit sig_upload_mod_finish(id,res,err);
            break;
        case Modules::DOWNLOADMOD:
            emit sig_download_mod_finish(id,res,err);
            break;
    }
}

HttpManage::~HttpManage()
{

}

void HttpManage::handleUpload(QUrl url, QString header, QByteArray body, ReqId req_id , Modules mod)
{
    PostHttpMultiPartReq(url, header, body, req_id, mod);
}

void HttpManage::showFileList(QUrl url)
{
    QNetworkRequest request(url);

    // 添加认证头（根据你的服务器需求）
    if (!_token.isEmpty())
    {
        request.setRawHeader("Authorization", "Bearer " + _token.toUtf8());
    }
    if (!_uid.isEmpty())
    {
        request.setRawHeader("X-User-UID", _uid.toUtf8());
    }
    // 发送GET请求
    QNetworkReply* reply = _manager.get(request);

    // 异步处理响应
    connect(reply, &QNetworkReply::finished, [this, reply]() {
        QNetworkReply::NetworkError error = reply->error();
        QVector<QJsonValue> fileList;

        // 处理网络错误
        if (error != QNetworkReply::NoError)
        {
            qDebug() << "Get file list error:" << reply->errorString();
            emit sig_file_list_received(fileList, ErrorCode::ERR_NETWORK);
            reply->deleteLater();
            return;
        }

        // 处理HTTP状态码
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if (statusCode != 200)
        {
            qDebug() << "HTTP Error:" << statusCode;
            emit sig_file_list_received(fileList, ErrorCode::ERR_SERVER);
            reply->deleteLater();
            return;
        }

        // 解析JSON响应
        QByteArray response = reply->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);

        if (!jsonDoc.isObject())
        {
            qDebug() << "Invalid JSON format";
            emit sig_file_list_received(fileList, ErrorCode::ERR_JSON);
            reply->deleteLater();
            return;
        }

        QJsonObject jsonObj = jsonDoc.object();
        QJsonArray filesArray = jsonObj["files"].toArray();
        //qDebug()<<"服务器返回的文件列表json为："<<jsonObj["files"];
        foreach (const QJsonValue &value, filesArray)
        {
            //qDebug()<<"服务器返回的文件列表json为："<<value.toString()<<'\n';
            fileList.push_back(value);
        }
        //qDebug()<<"服务器返回的文件列表json为："<<fileList<<'\n';

        emit sig_file_list_received(fileList, ErrorCode::SUCCESS);
        reply->deleteLater();
    });
}

